﻿using System;
using System.Configuration;
using System.IO;
using System.Security.Cryptography;
using System.Text;

namespace MyTimeLine.Util
{
    public static class Criptografia
    {
        #region Atributos

        private static byte[] _chave = { };
        private static readonly byte[] Iv = { 12, 34, 56, 78, 90, 102, 114, 126 };

        #endregion

        #region Propriedades

        public static string CryptoKey
        {
            get { return ConfigurationManager.AppSettings["CryptoKey"]; }
        }

        #endregion

        #region Criptografar

        public static string Criptografar(this string valor)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                MemoryStream ms = new MemoryStream();

                byte[] input = Encoding.UTF8.GetBytes(valor); _chave = Encoding.UTF8.GetBytes(CryptoKey.Substring(0, 8));

                CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(_chave, Iv), CryptoStreamMode.Write);
                cs.Write(input, 0, input.Length);
                cs.FlushFinalBlock();

                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw new ConfigurationErrorsException(Mensagens.Erro_Criptografia, ex);
            }
        }

        #endregion

        #region Descriptografar

        public static string Descriptografar(this string valor)
        {
            try
            {
                DESCryptoServiceProvider des = new DESCryptoServiceProvider();
                MemoryStream ms = new MemoryStream();

                byte[] input = Convert.FromBase64String(valor.Replace(" ", "+"));

                _chave = Encoding.UTF8.GetBytes(CryptoKey.Substring(0, 8));

                CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(_chave, Iv), CryptoStreamMode.Write);
                cs.Write(input, 0, input.Length);
                cs.FlushFinalBlock();

                return Encoding.UTF8.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                throw new ConfigurationErrorsException(Mensagens.Erro_Criptografia, ex);
            }
        }

        #endregion
    }
}
